package guoanmaker.operator.business.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import guoanmaker.operator.business.model.OperatorSensitiveWord;

/**
 * @author ws
 * @date 2017-11-27
 */

@Repository
public class OperatorSensitiveWordDao {

	@PersistenceContext
	EntityManager em;
	
	/**
	 * @description 查询t_operator_sensitiveword表中与word重复的个数，不包含id行记录
	 * @param word 敏感字
	 * @param id 敏感字id
	 * @return 重复个数
	 */
	public long countSameWord(String word, String id){
		String jpql = "select count(w.id) from OperatorSensitiveWord w where w.sensitivewordName=:word";
		if(id != null && id.trim().length() != 0){
			jpql += " and w.id<>:id";
		}
		
		Query query = em.createQuery(jpql);
		query.setParameter("word", word);
		if(id != null && id.trim().length() != 0){
			query.setParameter("id", id);
		}
		
		return (long)query.getSingleResult();
	}
	
	/**
	 * @description 根据敏感字模糊查询
	 * @param word 敏感字
	 * @param page 当前页数,从0开始
	 * @param size 页面中可显示记录数
	 * @return List<OperatorSensitiveWord>
	 */
	public List<OperatorSensitiveWord> findByWord(String word, String page, String size){
		String jpql = "select w from OperatorSensitiveWord w";
		if(word != null && word.trim().length() != 0){
			jpql += " where w.sensitivewordName like :word";
		}
		
		Query query = em.createQuery(jpql);
		if(word != null && word.trim().length() != 0){
			query.setParameter("word", word+"%");
		}
		int page1 = Integer.parseInt(page);
		int size1 = Integer.parseInt(size);
		query.setFirstResult(page1*size1);
		query.setMaxResults(size1);
		List<OperatorSensitiveWord> resultList = query.getResultList();
		return resultList;
	}

	public long totalLikeWord(String word){
		String jpql = "select count(w.id) from OperatorSensitiveWord w";
		if(word != null && word.trim().length() != 0){
			jpql += " where w.sensitivewordName like :word";
		}
		
		Query query = em.createQuery(jpql);
		if(word != null && word.trim().length() != 0){
			query.setParameter("word", word.trim()+"%");
		}
		
		return (long)query.getSingleResult();
	}
	
	
}
